<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Department extends CI_Model
{

    /**
     * 添加组织机构
     * @param $name
     * @param $parentId
     * @param $sort
     * @param $status
     * @return bool|CI_DB_active_record|CI_DB_result
     */
    public function add($data)
    {
         $this->db->insert('department', $data);
         $id=  $this->db->insert_id();
		 $dpt = ['uid'=> UID,'did'=>$id];
		 $this->db->insert('userDept',$dpt);
		 return $id;
    }


    /**
     * 修改部门
     * @param $id
     * @param $name
     * @param $parentId
     * @param $sort
     * @param $status
     * @return bool|CI_DB_active_record|CI_DB_result
     * @throws MyException
     */
    public function mod($data)
    {
        $update = $data;
        $update = array_filter($update, function ($var) {
            return $var !== null;
        });
        if (empty($update)) {
            throw new MyException('请至少修改一项', MyException::INPUT_ERR);
        }

        return $this->db->where('id', $data['id'])->update('department', $update);
    }

    /**
     * 删除部门ID
     * @param $deptId
     * @return bool
     */
    public function delete($deptId)
    {
        // 开启事务
        $this->db->trans_begin();

        // 删除部门ID
        $this->db->delete('department', ['id' => $deptId]);

        // 删除用户部门关联
        $this->db->delete('userDept', ['did' => $deptId]);

        // 事务提交
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
            return true;
        }
    }

    /**
     * 根据上级id获取组织信息及用户信息
     * @return array
     */
    public function getDeptTree()
    {
		if(!$this->auth->isAdmin()) $this->db->join('userDept','userDept.did=department.id and userDept.uid='.UID);
        $group = $this->db->select('department.id, department.name, department.parentId')
        ->order_by('sort','asc')->get('department')->result_array();
        $ids=[];
        $link=[];
        foreach ($group AS &$g) {
            $ids[]=$g['id'];
            $link[$g['id']]=&$g;
        }
		unset($g);
        $res=[];
        foreach ($group AS &$g) {
            if (in_array($g['parentId'],$ids)){
                $link[$g['parentId']]['children'][]=&$g;
            }else {
                $res[]=&$g;
            }
        }
        return $res;
    }

    /**
     * 通过ID,返回部门名称
     * @param  array  $idArr [id数组]
     * @return [string]        [部门的字符串]
     */
    public function deptNameByID(array $idArr)
    {
        $data = $this->db->select('name')->where_in('id',$idArr)->get('department')->result_array();
        $str = '';
        foreach($data as $v)
        {
            $str .= $v['name'].";";
        }
        return $str;
    }
}
